/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Examples;

import homomorphism.list.ThirdHomomorphismTheoremEx;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.hadoop.io.LongWritable;

/**
 *
 * @author liuyu
 * It's a more efficient version of SUM because  fold(Iterator<LongWritable> values) will be more efficient than
 *  fold(ArrayList<LongWritable> values) in this framework.
 */
public class SUM3 extends ThirdHomomorphismTheoremEx<LongWritable, LongWritable> {

    @Override
    public LongWritable fold(Iterator<LongWritable> values) {
        return sum(values);
    }

    @Override
    public ArrayList<LongWritable> unfold(final LongWritable value) {
        return new ArrayList<LongWritable>() {
            {  add(value);  }
        };
    }

    public static LongWritable sum(Iterator<LongWritable> xs) {
        Long rst = 0l;
        while (xs.hasNext()) {
            rst += xs.next().get();
        }
        return new LongWritable(rst);
    }

}
